class Staffer < ActiveRecord::Base
  belongs_to :store
  attr_accessor :password, :password_confirmation
  validates_presence_of :password, if: :password_required?
  validates :login_name, uniqueness: { message: "手机号已经存在!" }#, length: { is: 11 }
  # validates :password, confirmation: true, unless: ->(staff){staff.password.blank?}
  before_create :encrypt_password
  def encrypt_with_salt(txt,salt)
    Digest::SHA256.hexdigest("#{txt}#{salt}")
  end

  def password_connection?
    self.encrypted_password == self.encrypt_with_salt(self.password, self.salt)
  end

  private
  def encrypt_password
    self.salt = Digest::MD5.hexdigest("--#{Time.now.to_i}--")
    self.encrypted_password = self.encrypt_with_salt(self.password, self.salt)
  end

  def password_required?
     !password.nil? || !persisted? || !password_confirmation.nil?
  end
end
